package com.mask.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 密码加密工具类
 * @author hx
 * @date 2021/10/15 5:31 下午
 */

public class Md5Utils {

    private static final Logger logger = LoggerFactory.getLogger(Md5Utils.class);
    /**
     * 密码md5加密
     * @param source 明文密码
     * @return 密文密码
     */
    public static String md5(String source){
        //1.判断source是否有效
        if (source == null || source.length() == 0){
            //2.如果不是有效的字符串抛出异常
            throw new RuntimeException("字符串不合法，请不要传入空字符串!");
        }
        //3.获取messageDigest对象
        String algorithm ="md5";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            //4.获取明文字符串对应的字节数组
            byte[] input = source.getBytes();
            //5.执行加密
            byte[] output = messageDigest.digest(input);
            //6.创建BigInteger对象
            int signum =1;
            BigInteger bigInteger = new BigInteger(signum, output);
            //7.按照十六进制将bigInteger的值转换成字符串
            int radix =16;
            String encoded = bigInteger.toString(radix).toUpperCase();

            return encoded;
        } catch (NoSuchAlgorithmException e) {
            logger.warn("[{}]密码转换失败",source);
            e.printStackTrace();

        }
        return null;
    }
}
